<!--  -->
<template>
  <div class="">
    <el-card>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
        <el-breadcrumb-item>添加用户</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form
        :model="userAddDatas"
        ref="userAdd"
        :rules="userAddRules"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="userAddDatas.username"
                placeholder="用户名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="密码">
              <el-input
                v-model="userAddDatas.password"
                placeholder="密码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="年龄">
              <el-input
                v-model="userAddDatas.age"
                placeholder="年龄"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号">
              <el-input
                v-model="userAddDatas.phone"
                placeholder="手机号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户头像">
              <el-upload
                class="avatar-uploader"
                action="/api/admin/user/uploadimg"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="imageUrl"
                  :src="'http://localhost:3000' + imageUrl"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户地址">
              <el-input
                v-model="userAddDatas.address"
                type="textarea"
                placeholder=""
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户地址">
              <el-radio
                v-model="userAddDatas.level"
                :label="level.id"
                v-for="level in levelList"
                :key="level.id"
                >{{ level.title }}</el-radio
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否可用">
              <el-switch
                v-model="userAddDatas.is_show"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="可用"
                inactive-text="禁用"
                active-value="1"
                inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="">
              <el-button type="primary" @click="addUserFn('userAdd')"
                >添加用户</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import tools from "@/utils/tools.js";
import { UserAddApi } from "@/api/user";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  //ComponentName和文件名保持一致
  name: "ComponentName",
  data() {
    // 自定义校验规则
    var validateUserName = (rule, value, callback) => {
      if (value === "") {
        // value 指的是用户输入的数据
        callback(new Error("用户名不能为空"));
      } else {
        if (!(tools.regPhone.test(value) || tools.regEmail.test(value))) {
          callback(new Error("用户名格式不正确"));
        }
        callback();
      }
    };
    //这里存放数据
    return {
      imageUrl: "",
      userAddDatas: {
        username: "",
        password: "",
        age: "",
        phone: "",
        address: "",
        is_show: "1",
        level: "1",
        img: "",
      },
      levelList: [
        {
          id: "1",
          title: "管理员",
        },
        {
          id: "2",
          title: "金牌用户",
        },
        {
          id: "3",
          title: "银牌用户",
        },
        {
          id: "4",
          title: "铜牌用户",
        },
      ],
      userAddRules: {
        username: [{ validator: validateUserName, trigger: "blur" }],
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    handleAvatarSuccess(res) {
      console.log(res);
      this.$set(this.userAddDatas, "img", res.data.pic);
      this.imageUrl = res.data.pic;
    },
    beforeAvatarUpload(file) {
      console.log(file);
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    addUserFn(formName) {
      //点击添加用户按钮
      this.$refs[formName].validate((valid) => {
        if (valid) {
          UserAddApi(this.userAddDatas).then((result) => {
            console.log(result);
            if (result.data.status == 200) {
              this.$router.push("/admin/userlist");
            } else {
              this.$message({
                message: result.data.msg,
                type: "warning",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  deactivated() {}, //如果页面有keep-alive缓存功能，当组件被移除时，触发钩子函数deactivated
};
</script>
<style>
</style>